const nodemailer = require('nodemailer');
const config = require('../config');

/**
 * 邮件服务类
 * 负责发送邮件相关功能
 */
class EmailService {
  constructor() {
    this.transporter = null;
    this.init();
  }

  /**
   * 初始化邮件传输器
   */
  init() {
    try {
      this.transporter = nodemailer.createTransporter({
        host: process.env.SMTP_HOST || 'smtp.qq.com',
        port: process.env.SMTP_PORT || 587,
        secure: false, // true for 465, false for other ports
        auth: {
          user: process.env.SMTP_USER || 'hfqf123@qq.com',
          pass: process.env.SMTP_PASS || 'your_app_password'
        }
      });

      console.log('✅ 邮件服务初始化成功');
    } catch (error) {
      console.error('❌ 邮件服务初始化失败:', error);
    }
  }

  /**
   * 验证邮件配置
   */
  async verifyConnection() {
    try {
      await this.transporter.verify();
      console.log('✅ 邮件服务连接验证成功');
      return true;
    } catch (error) {
      console.error('❌ 邮件服务连接验证失败:', error);
      return false;
    }
  }

  /**
   * 发送邮件
   * @param {Object} options - 邮件选项
   * @param {string} options.to - 收件人邮箱
   * @param {string} options.subject - 邮件主题
   * @param {string} options.text - 邮件文本内容
   * @param {string} options.html - 邮件HTML内容
   * @param {Array} options.attachments - 附件列表
   */
  async sendMail(options) {
    try {
      const mailOptions = {
        from: `"医院预约系统" <${process.env.SMTP_USER || 'your_email@qq.com'}>`,
        to: options.to,
        subject: options.subject,
        text: options.text,
        html: options.html,
        attachments: options.attachments || []
      };

      const result = await this.transporter.sendMail(mailOptions);
      console.log('✅ 邮件发送成功:', result.messageId);
      return { success: true, messageId: result.messageId };
    } catch (error) {
      console.error('❌ 邮件发送失败:', error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 发送预约数据Excel文件
   * @param {string} to - 收件人邮箱
   * @param {Buffer} excelBuffer - Excel文件缓冲区
   * @param {string} fileName - 文件名
   * @param {Object} dataInfo - 数据信息
   */
  async sendAppointmentReport(to, excelBuffer, fileName, dataInfo) {
    const subject = `医院预约数据报告 - ${dataInfo.date}`;
    
    const html = `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
        <h2 style="color: #2c3e50;">医院预约数据报告</h2>
        <div style="background-color: #f8f9fa; padding: 20px; border-radius: 5px; margin: 20px 0;">
          <h3 style="color: #495057; margin-top: 0;">报告信息</h3>
          <p><strong>报告日期:</strong> ${dataInfo.date}</p>
          <p><strong>医院名称:</strong> ${dataInfo.hospitalName}</p>
          <p><strong>总预约数:</strong> ${dataInfo.totalAppointments}</p>
          <p><strong>已确认预约:</strong> ${dataInfo.confirmedAppointments}</p>
          <p><strong>待确认预约:</strong> ${dataInfo.pendingAppointments}</p>
          <p><strong>已取消预约:</strong> ${dataInfo.cancelledAppointments}</p>
          <p><strong>已完成预约:</strong> ${dataInfo.completedAppointments}</p>
        </div>
        <div style="background-color: #e9ecef; padding: 15px; border-radius: 5px;">
          <p style="margin: 0; color: #6c757d;">
            此邮件由医院预约系统自动发送，请查看附件中的详细数据。
          </p>
        </div>
      </div>
    `;

    const text = `
医院预约数据报告

报告日期: ${dataInfo.date}
医院名称: ${dataInfo.hospitalName}
总预约数: ${dataInfo.totalAppointments}
已确认预约: ${dataInfo.confirmedAppointments}
待确认预约: ${dataInfo.pendingAppointments}
已取消预约: ${dataInfo.cancelledAppointments}
已完成预约: ${dataInfo.completedAppointments}

此邮件由医院预约系统自动发送，请查看附件中的详细数据。
    `;

    return await this.sendMail({
      to,
      subject,
      text,
      html,
      attachments: [{
        filename: fileName,
        content: excelBuffer,
        contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }]
    });
  }

  /**
   * 发送测试邮件
   * @param {string} to - 收件人邮箱
   */
  async sendTestEmail(to) {
    const subject = '医院预约系统 - 测试邮件';
    const text = '这是一封测试邮件，用于验证邮件服务配置是否正确。';
    const html = '<h2>医院预约系统 - 测试邮件</h2><p>这是一封测试邮件，用于验证邮件服务配置是否正确。</p>';

    return await this.sendMail({
      to,
      subject,
      text,
      html
    });
  }
}

module.exports = new EmailService();
